<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='search'>
        <a-row :gutter='24'>
<!--          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label='领用基地'>
              <a-select v-model='queryParams.sourceBase' placeholder='请选择领用基地' @change='sourceBaseChange'>
                <a-select-option v-for='(d,i) in sourceBaseList' :key='d.id' :value='d.id'>{{
                    d.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label='领用大棚'>
              <a-select v-model='queryParams.sourceGreenhouse' placeholder='请选择领用大棚'>
                <a-select-option v-for='(d,i) in sourceGreenhouseList' :key='d.id' :value='d.id'>{{
                    d.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>-->
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='领用单号'>
              <a-input placeholder='请输入领用单号' v-model='queryParams.no'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='领用人'>
              <a-input placeholder='请输入领用人' v-model='queryParams.outPersonName'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='冷库'>
              <a-select v-model='queryParams.storehouse' placeholder='请选择冷库'>
                <a-select-option v-for='d in hoseList' :key='d.id' :value='d.code'>{{ d.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if='toggleSearchStatus'>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='领用时间'>
                <a-range-picker :style="{width: '100%'}"  format="YYYY-MM-DD"
                                :placeholder="['开始时间', '结束时间']"
                                v-model='rangePikerDate'
                                @change="onQueryDateChange" />
              </a-form-item>
            </a-col>

            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='状态'>
                <a-select v-model='queryParams.state' placeholder='请选择状态'>
                  <a-select-option v-for='(d,i) in stateList' :key='d.id' :value='d.id'>{{ d.value }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <span style='float: left;overflow: hidden;' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='search' icon='search'>查询</a-button>
              <a-button type='primary' @click='resetSearch' icon='reload' style='margin-left: 8px'>重置</a-button>
              <a @click='handleToggleSearch' style='margin-left: 8px'>
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-button type='primary' icon='download' @click="handleExportXls('采后物资出库主表')">导出</a-button>
      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='materialDeleteBatch(selectedRowKeys)'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'> 批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
        style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        size='middle'
        bordered
        rowKey='id'
        class='j-table-force-nowrap'
        :columns='columns'
        :dataSource='mainDataSource'
        :pagination='mainPagination'
        :loading='loading'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        @change='mainPaginationChange'>

        <template slot='htmlSlot' slot-scope='text'>
          <div v-html='text'></div>
        </template>
        <template slot='imgSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无图片</span>
          <img v-else :src='getImgView(text)' height='25px' alt=''
               style='max-width:80px;font-size: 12px;font-style: italic;' />
        </template>
        <template slot='fileSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无文件</span>
          <a-button
            v-else
            :ghost='true'
            type='primary'
            icon='download'
            size='small'
            @click='uploadFile(text)'>
            下载
          </a-button>
        </template>

        <span slot='action' slot-scope='text, record'>
          <a-button type='primary' v-if='record.state===1' @click='editModalShow(record)'>库管确认</a-button>
          <a-button type='primary' v-if='record.state===2' @click='exportExcel(record)'>导出出库单</a-button><a-divider type='vertical' />
          <a-button type='danger' v-if='record.state===2' @click='editModalShow(record)'>撤销库管确认</a-button>
        </span>

      </a-table>
    </div>


    <!-- 第一个弹窗   <flowerMaterialOutMain-modal ref="modalForm" @ok="modalFormOk"></flowerMaterialOutMain-modal>-->
    <a-modal v-model:visible='addOrEditVisible' width='80%' :title='firstModalTitle' @ok='materialAddOrEdit'
             :maskClosable='false'>
      <div>
        <a-row>
          <a-col :span='8'>
            <div style='display: inline-block'>单号：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input v-model='material.no' placeholder='自动生成' style='width: 100%'  disabled/>
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block;'>账期：</div>
            <div style='display: inline-block;'>
              <a-radio-group v-model='material.period' @change='periodChange' disabled>
                <a-radio v-for='(item,index) in periodList' :value='item'>{{ item}}</a-radio>
              </a-radio-group>
            </div>
          </a-col>
<!--          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>领用基地：</div>
            <div style='display: inline-block;width:60%'>
              <a-select v-model='material.sourceBase' placeholder='请选择领用基地' style='width: 100%;' @change='sourceBaseChange' disabled>
                <a-select-option v-for='(d,i) in sourceBaseList' :key='d.id' :value='d.id'>{{
                    d.name
                  }}
                </a-select-option>
              </a-select>
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>领用大棚：</div>
            <div style='display: inline-block;width:60%'>
              <a-select v-model='material.sourceGreenhouse' placeholder='请选择领用大棚' style='width: 100%;' disabled>
                <a-select-option v-for='(d,i) in sourceGreenhouseList' :key='d.id' :value='d.id'>{{
                    d.name
                  }}
                </a-select-option>
              </a-select>
            </div>
          </a-col>-->
        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>冷库：</div>
            <div style='display: inline-block;width: 60%'>
              <a-select v-model:value='material.storehouse' style='width: 100%;' placeholder='请选择冷库' disabled>
                <a-select-option v-for='d in hoseList' :key='d.id' :value='d.code'>{{ d.name }}</a-select-option>
              </a-select>

            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>领用人：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input v-model='material.outPersonName' placeholder='请输入领用人' style='width: 100%' disabled/>
            </div>
          </a-col>

          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>领用时间：</div>
            <div style='display: inline-block;width: 60%'>
              <a-date-picker v-model:value='material.outTime'
                             :default-value='moment(defaultoutTime, dateFormat)' :valueFormat='dateFormat'
                             placeholder='请选择出库时间' disabled/>
            </div>
          </a-col>
        </a-row>
        <a-row style='margin-top: 10px'>

        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='24'>
            <div style='display: inline-block;'>备注：</div>
            <div style='display: inline-block;width: 85%'>
              <a-textarea v-model='material.remarks' placeholder='请输入备注' disabled/>
            </div>
          </a-col>
        </a-row>
      </div>
      <a-divider />
      <div style='margin-top: -20px'>
        <div style='font-size: 20px;color: #0742f3;margin-bottom: 3px'>物资</div>
        <!--        <a-button style='display: inline-block' type='primary' icon='plus' @click='materialModalShow'>新增</a-button>-->
        <div style='display: inline-block;margin-left: 10px'>
          <span style='font-size: 14px;color: black;'>总价合计：</span><span
          style='color: red;margin-right: 20px'>{{ allTotalPrice }}</span>
          <span style='font-size: 14px;color: black;'>数量合计：</span><span style='color: red'>{{ allTotalNum }}</span>
        </div>
        <div style='margin-top: 7px'>
          <a-table :columns='materialColumns' :data-source='materialDataSource'
                   bordered row-key='uuid'
                   :loading='materialLoading'
                   :scroll='{ x: true, y: 300 }'>
            <template v-for="colNum in ['num']" :slot='colNum' slot-scope='text, record, index'>
              <div :key='colNum' style='float: left;margin-right: 0;width: 100%'>
                <input v-model:value='record.num' placeholder='请输入数量' style='width: 100%;'
                       @change='numberChange(record,record.num,record.price)' disabled />
              </div>
            </template>

            <!--            <template slot='operation' slot-scope='text, record'>
                          <a-popconfirm v-if='materialDataSource.length' title='确定删除?'
                                        @confirm='() => materialCategorysDelete(record.uuid)'>
                            <a>删除</a>
                          </a-popconfirm>
                        </template>-->
          </a-table>
        </div>
      </div>
      <!-- 操作按钮-->
      <template slot='footer'>
        <div style='display: inline-block;margin: 0px 10px'>
          <a-popconfirm title='是否确认入库?' @confirm='() => materialAddOrEdit()'>
            <a-button type='primary' v-if='material.state===1'>库管确认</a-button>
          </a-popconfirm>
          <a-popconfirm title='是否确认撤销入库?' @confirm='() => HouseSureBack()'>
            <a-button type='danger' v-if='material.state===2'>撤销库管确认</a-button>
          </a-popconfirm>
        </div>
      </template>
    </a-modal>
  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import FlowerMaterialOutMainModal from './modules/FlowerMaterialOutMainModal'
import JDate from '@/components/jeecg/JDate.vue'
import '@/assets/less/TableExpand.less'
import { downFile } from '@/api/manage'
import {
  getFlowerMaterialBook,
  getFlowerMaterialBook1,
  getFlowerMaterialOutMain,
  getFlowerMaterialOutInfoByMainId,
  flowerMaterialOutMainAdd,
  flowerMaterialOutMainEdit,
  flowerMaterialOutMainDelete,
  flowerMaterialOutMainDeleteBatch,
  getFlowerStorehouseDict,
  flowerMaterialOutHouseSure,
  flowerMaterialOutHouseSureBack,
  queryFlowerBase,
  queryGreenhouseByPd,
  period,
} from '@/api/api'
import moment from 'moment'
import { getTodayDate } from '../../utils/getDate'
import { getUuid } from '../../utils/uuid'
import { ifInteger, ifNumber, ifNumber1 } from '../../utils/ifNumber'

export default {
  name: 'FlowerMaterialOutHouseSure',
  mixins: [JeecgListMixin],
  components: {
    JDate,
    FlowerMaterialOutMainModal
  },
  data() {
    return {
      description: '采后物资出库主表管理页面',
      hoseList: [],
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '领用单号',
          align: 'center',
          dataIndex: 'no'
        },{
          title:'账期',
          align:"center",
          width:100,
          dataIndex: 'period'
        },
        /*{
          title:'领用基地',
          align:"center",
          width:120,
          dataIndex: 'sourceBase_dictText'
        },
        {
          title:'领用大棚',
          align:"center",
          width:120,
          dataIndex: 'sourceGreenhouse_dictText'
        },*/
        {
          title: '库房',
          align: 'center',
          dataIndex: 'storehouse_dictText'
        },
        {
          title: '领用人',
          align: 'center',
          dataIndex: 'outPersonName'
        },
        {
          title: '领用时间',
          align: 'center',
          dataIndex: 'outTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '领导确认人',
          align: 'center',
          dataIndex: 'leaderSureUser'
        },{
          title: '库管确认人',
          align: 'center',
          dataIndex: 'houseSureUser'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'state',
          customRender: function(text) {
            let stateString = ''
            switch (text) {
              case 0:
                stateString = '录入'
                break
              case 1:
                stateString = '领导确认'
                break
              case 2:
                stateString = '库管确认'
                break
              default:
                stateString = '未知'
            }
            return stateString
          }
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createBy_dictText'
        },
        {
          title: '创建日期',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/flowermater/flowerMaterialOutMain/list',
        delete: '/flowermater/flowerMaterialOutMain/delete',
        deleteBatch: '/flowermater/flowerMaterialOutMain/deleteBatch',
        exportXlsUrl: '/flowermater/flowerMaterialOutMain/exportXls',
        importExcelUrl: 'flowermater/flowerMaterialOutMain/importExcel'
      },
      dictOptions: {},
      mainDataSource: [],//主页面中的数据源
      addOrEditVisible: false,//是否打开新增或编辑的弹窗
      selectMaterialVisible: false,//是否打开物资选择的弹窗
      firstModalTitle: '',//第一个弹窗中的标题
      addOrEditFlag: 'add',//打开的弹窗是新增还是编辑的标识
      material: {//第一个弹窗中的主表数据
        period:'',//账期
        outPersonName: '',//领用人
        outPersonCode: '',//领用人编码
        name: '',//领用单名称
        outTime: '',//领用时间
        storehouse: '',//冷库
        type: '',//领用类型
        contractNo: '',//合同编号
        remarks: '',//备注
        /*sourceBase: '',//领用基地
        sourceGreenhouse: '',//领用大棚*/
      },
      sourceBaseList:[],//领用基地列表
      sourceGreenhouseList:[],//领用大棚列表
      storehouseList: [],//冷库列表
      materialTypeList: [],//领用类型列表
      defaultoutTime: '',
      dateFormat: 'YYYY-MM-DD',
      materialColumns: [// 第一个弹窗中表格的表头
        {
          title: '物资名称',
          dataIndex: 'name',
          align: 'center',
          width: 100
        },
        {
          title: '物资编码',
          dataIndex: 'code',
          align: 'center',
          width: 100
        }, {
          title: '规格',
          dataIndex: 'specs',
          align: 'center',
          width: 140
        }, {
          title: '型号',
          dataIndex: 'modelname',
          align: 'center',
          width: 140
        }, {
          title: '领用单位',
          dataIndex: 'unit',
          align: 'center',
          width: 90
        }, {
          title: '计量单位',
          dataIndex: 'unitMeasure',
          align: 'center',
          width: 90
        }, {
          title: '数量',
          dataIndex: 'num',
          scopedSlots: { customRender: 'num' },
          align: 'center',
          width: 120
        }, {
          title: '单价',
          dataIndex: 'price',
          align: 'center',
          width: 120
        }, {
          title: '总价',
          dataIndex: 'totalPrice',
          align: 'center',
          width: 140
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      materialDataSource: [],//第一个弹窗中的数据源
      allTotalPrice: 0,//第一个弹窗中所有商品的总价
      allTotalNum: 0,//第一个弹窗中所有商品的总数量
      selectMaterialColumns: [// 第二个弹窗中表格的表头
        {
          title:'库房',
          align:"center",
          dataIndex: 'storehouse_dictText',
          width: 100,
        },{
          title: '物资名称',
          dataIndex: 'name',
          align:"center",
          width: 100,
        },
        {
          title: '物资编码',
          dataIndex: 'code',
          align:"center",
          width: 100,
        }, {
          title: '规格',
          dataIndex: 'specs',
          align:"center",
          width: 100,
        }, {
          title: '型号',
          dataIndex: 'modelname',
          align:"center",
          width: 100,
        }, {
          title: '领用单位',
          dataIndex: 'unit',
          align:"center",
          width: 90,
        }, {
          title: '计量单位',
          dataIndex: 'unitMeasure',
          align:"center",
          width: 90,
        },
        {
          title:'总数量',
          align:"center",
          dataIndex: 'totalNum',
          width: 80,
        },
        {
          title:'剩余数量',
          align:"center",
          dataIndex: 'num',
          width: 100,
        },{
          title:'单价',
          align:"center",
          dataIndex: 'price',
          width: 100,
        },{
          title:'总价',
          align:"center",
          dataIndex: 'totalPrice',
          width: 100,
        },
      ],
      materialCategorysFlag: true,//选中编辑的领用单是否已经有物资，true为是，false为否
      mainPagination: {// 主页表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      selectMaterialPagination: {//选择物资弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 5,//每页中显示5条数据
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      selectMaterialDataSource: [],//第二个弹窗中的数据源
      selectMaterialCategorys: [],//第二个弹窗中已选择的物资
      materialLoading: false,//是否显示第一个弹窗中表格的加载状态
      selectMaterialLoading: false,//是否显示第二个弹窗中表格的加载状态
      queryParams: {// 主页查询
        no: '',//领用单号
        outPersonName: '',//领用人
        storehouse: '',//冷库
        state: '',//状态
        sDate:'',//开始时间
        eDate:'',//结束时间
      },
      rangePikerDate:[],
      stateList: [{ id: 0, value: '录入' }, { id: 1, value: '领导确认' }, { id: 2, value: '库管确认' }],
      queryMaterialCategorysParams: {// 物资选择弹窗的查询
        name: '',// 物资名称
        code: ''// 物资编码
      },
      periodList:[],//从后台取回的账期列表（上个账期，当前账期，下个账期）
    }
  },
  created() {
    //获取冷库列表
    this.hoseList = JSON.parse(localStorage.getItem('ch_storehouse') ? localStorage.getItem('ch_storehouse') : '')
    this.getPeriod()
  },
  mounted() {
    this.todayDate()
    this.queryMaterialOutMain()
    this.queryFlowerBase()
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    moment,
    initDictConfig() {
    },
    search() {// 主页中根据条件查询
      this.mainPagination.current=1
      this.queryMaterialOutMain()
    },
    onQueryDateChange(date, dateString){// 日期段选择改变时的回调
      this.queryParams.sDate = dateString[0]
      this.queryParams.eDate = dateString[1]
    },
    resetSearch() {// 重置查询
      this.queryParams = {// 主页查询
        no: '',//领用单号
        outPersonName: '',//领用人
        storehouse: '',//冷库
        state: '',//状态
        sDate:'',//开始时间
        eDate:'',//结束时间
      }
      this.rangePikerDate=[]
      this.search()
    },
    searchMaterialCategorys() {// 物资选择弹窗中的物资
      this.selectMaterialPagination.current=1
      this.queryFlowerMaterialCategorys()
    },
    queryMaterialOutMain() {//获取物资领用单数据
      this.loading = true
      this.materialDataSource.length = 0
      let params = {
        pageNo: this.mainPagination.current,
        pageSize: this.mainPagination.pageSize
      }
      params={...this.queryParams,...params}
      getFlowerMaterialOutMain(params).then(res => {
        if (res.success) {
          this.mainPagination.total = res.result.total
          this.mainDataSource = res.result.records
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },

    mainPaginationChange(pagination) {
      this.mainPagination.current = pagination.current
      this.mainPagination.pageSize = pagination.pageSize
      this.queryMaterialOutMain()
    },
    addModalShow() {//打开第一个弹窗(新增)
      this.addOrEditFlag = 'add'
      this.firstModalTitle = '新增'
      this.material = {
        period:'',//账期
        outPersonName: '',//领用人
        outPersonCode: '',//领用人编码
        name: '',//领用单名称
        outTime: '',//领用时间
        storehouse: '',//冷库
        type: '',//领用类型
        contractNo: '',//合同编号
        remarks: ''//备注
      },
        this.todayDate()
      this.allTotalPrice = 0
      this.allTotalNum = 0
      this.materialDataSource = []
      this.addOrEditVisible = !this.addOrEditVisible
    },
    editModalShow(record) {//打开第一个弹窗(编辑)
      this.addOrEditFlag = 'edit'
      this.firstModalTitle = '编辑'
      this.material = record
      this.selectMaterialDataSource.length = 0
      this.allTotalPrice = 0
      this.allTotalNum = 0
      //this.sourceBaseChange(record.sourceBase)
      this.queryFlowerMaterialDetailByMainId(record.id)
      this.addOrEditVisible = !this.addOrEditVisible
    },
    materialModalShow() {//打开第二个弹窗
      /*设置下面这两行是为了处理再次打开商品选择弹窗时，
      还会在界面上保留上次选择物资而实际上没有选择任何物资的问题*/
      this.selectedRowKeys.length = 0
      this.selectionRows.length = 0
      if (!this.material.storehouse) {
        this.$message.error('请先选择冷库')
        return
      }
      this.selectMaterialPagination = {//选择物资弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 5,//每页中显示5条数据
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }
      this.selectMaterialCategorys = []
      this.queryFlowerMaterialCategorys()
      this.selectMaterialVisible = !this.selectMaterialVisible
    },
    queryFlowerMaterialDetailByMainId(id) {//获取第一个弹窗中的物资信息
      this.materialLoading = true
      let params = {
        id: id
      }
      getFlowerMaterialOutInfoByMainId(params).then(res => {
        if (res.success) {
          this.materialDataSource = res.result

          this.materialDataSource.map(item => {
            item.uuid = getUuid()
          })

          if (this.materialDataSource.length > 0) {
            this.materialCategorysFlag = true
          } else {
            this.materialCategorysFlag = false
          }

          for (let item of this.materialDataSource) {
            this.allTotalPrice += item.totalPrice * 10 / 10// 计算总价合计
            this.allTotalNum += item.num * 10 / 10// 计算数量合计
          }
          this.allTotalPrice = this.allTotalPrice.toFixed(2)
        } else {
          this.$message.error(res.message)
        }
        this.materialLoading = false
      })
    },
    queryFlowerMaterialCategorys() {//获取第二个弹窗中的物资类型
      this.selectMaterialLoading = true
      if (!this.material.storehouse) {
        this.$message.error('请先选择冷库')
        return
      } else {
        this.selectMaterialLoading = true
        let params = {
          storehouse: this.material.storehouse,
          pageNo: this.selectMaterialPagination.current,
          pageSize: this.selectMaterialPagination.pageSize
        }
        params = { ...this.queryMaterialCategorysParams, ...params }
        getFlowerMaterialBook(params).then(res => {
          if (res.success) {
            this.selectMaterialPagination.total = res.result.total
            this.selectMaterialDataSource = res.result.records
            //将uuid封装进selectMaterialDataSource中的各物资对象中,为第一个弹窗table中的key使用
            this.selectMaterialDataSource.map(item => {
              item.uuid = getUuid()
              item.maxNum = item.num
            })
          } else {
            this.$message.error(res.message)
          }
          this.selectMaterialLoading = false
        })
      }
    },

    materialCategorysOnChange(selectedRowKeys, selectionRows) {//第二个弹窗中选择物资时的回调
      this.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法多选
      this.selectionRows = selectionRows
    },
    materialCategorysOnSelect(record, selected, selectedRows) {//选择/取消选择某个商品的回调
      if (selected) {//如果是选择某个商品的操作，就将所选择的商品添加进selectMaterialCategorys
        this.selectMaterialCategorys.push(record)
      } else {//如果是取消选择某个商品的操作，则从selectMaterialCategorys中删除相应的商品
        this.selectMaterialCategorys = this.selectMaterialCategorys.filter(item => item.id !== record.id)
      }
    },
    materialCategorysOnSelectAll(selected, selectedRows, changeRows) {//选择/取消选择所有商品的回调
      if (selected) {//如果是选择所有商品的操作，就将所选择的商品添加进selectMaterialCategorys
        this.selectMaterialCategorys = [...this.selectMaterialCategorys, ...changeRows]
      } else {//如果是取消选择所有商品的操作，则从selectMaterialCategorys中删除相应的商品
        for (let i of changeRows) {
          this.selectMaterialCategorys = this.selectMaterialCategorys.filter(item => item.id !== i.id)
        }
      }
    },
    materialCategorysAdd() {// 第二个弹窗中的确定选择物资
      /*let haveMaterialFlag = false//第一个弹窗中是否已包含所选择物资的标识
      for (let item1 of this.materialDataSource) {
        for (let item2 of this.selectMaterialCategorys) {
          if (item2.code === item1.code) {
            this.$message.error(`该领用物资单中已有物资编码为:${item1.code}的物资`)
            haveMaterialFlag = true
            return
          }
        }
      }
      if (!haveMaterialFlag) {
        this.materialDataSource = [...this.materialDataSource, ...this.selectMaterialCategorys]
      }*/

      this.selectMaterialCategorys.map(item => {
        delete item.id//第一个弹窗表格中的物资不能将id传到后台
      })
      this.materialDataSource = [...this.materialDataSource, ...this.selectMaterialCategorys]
      this.allTotalNum = 0
      this.allTotalPrice = 0
      for (let i = 0; i < this.materialDataSource.length; i++) {
        this.allTotalNum += this.materialDataSource[i].num* 10 / 10
        this.allTotalPrice += this.materialDataSource[i].totalPrice* 10 / 10
      }
      this.allTotalPrice = (this.allTotalPrice * 10 / 10).toFixed(2)
      this.selectMaterialVisible = !this.selectMaterialVisible
    },
    selectMaterialPaginationChange(pagination) {
      this.selectMaterialPagination.current = pagination.current
      this.selectMaterialPagination.pageSize = pagination.pageSize
      this.queryFlowerMaterialCategorys()
    },
    materialAddOrEdit() {// 库管确认
      let that = this
      let allNumberFlag = true//是否所有的商品都有数量的标识
      let allTotalPriceFlag = true//是否所有的商品都有总价的标识
      if (this.material.outPersonName === '') {
        this.$message.error('请输入领用人')
      } else if (this.material.outTime === '') {
        this.$message.error('请选择领用时间')
      } else if (this.material.storehouse === '') {
        this.$message.error('请选择冷库')
      } else if (this.materialDataSource.length === 0) {
        this.$message.error('至少需要有一个领用物资')
      } else {
        for (let item of this.materialDataSource) {
          if (item.num === '' || item.num === null) {
            this.$message.error('请输入数量')
            allNumberFlag = false
            return
          }
          if (!ifNumber1(item.num)) {
            this.$message.error('数量必须为数字')
            return
          }
        }
        for (let item of this.materialDataSource) {
          if (item.totalPrice === '' || item.totalPrice === null) {
            this.$message.error('请输入总价')
            allTotalPriceFlag = false
            return
          }
          if (!ifNumber(item.totalPrice)) {
            this.$message.error('总价必须为数字')
            allTotalPriceFlag = false
            return
          }
        }

        // 去掉materialDataSource中每个对象（如果有）的uuid，此uuid是在前端生成的
        this.materialDataSource.map(item => {
          delete item.uuid
        })
        this.material.flowerMaterialOutList = this.materialDataSource//将物资信息封装进material中
        if( this.material.houseSureUser){
          this.$message.success("库管已经确认过了")
        }
        flowerMaterialOutHouseSure(this.material).then(res => {
          if (res.success) {
            that.queryMaterialOutMain()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
          this.addOrEditVisible = false
        })
      }
    },
    materialDelete(id) {
      flowerMaterialOutMainDelete({ id: id }).then(res => {
        if (res.success) {
          this.queryMaterialOutMain()
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    materialDeleteBatch(selectedRowKeys) {
      if (selectedRowKeys.length > 0) {
        let ids = ''
        for (let item of selectedRowKeys) {
          ids = ids + item + ','
        }
        flowerMaterialOutMainDeleteBatch({ ids: ids }).then(res => {
          if (res.success) {
            this.queryMaterialOutMain()
            this.selectedRowKeys.length = 0
            this.$message.success('批量删除成功')
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    materialCategorysDelete(id) {
      const dataSource = [...this.materialDataSource]
      this.materialDataSource = dataSource.filter(item => item.uuid !== id)

      // 计算出合计总价、合计数量
      this.allTotalPrice = 0
      this.allTotalNum = 0
      for (let item of this.materialDataSource) {
        if (ifNumber1(item.num)) {
          this.allTotalPrice += item.totalPrice * 10 / 10
          this.allTotalNum += item.num * 10 / 10
        } else {
          this.allTotalPrice = null
          this.allTotalNum = null
          return
        }
      }
      this.allTotalPrice = (this.allTotalPrice * 10 / 10).toFixed(2)
    },
    todayDate() {// 设置新增弹窗中的领用时间的默认值为当前日期
      this.defaultoutTime = getTodayDate()
      this.material.outTime = getTodayDate()
    },

    numberChange(record, number, price) {
      if (ifNumber1(number) && (number !== null || number !== '') && (price !== null || price !== '')) {
        if ((number * 10 / 10) > (record.maxNum * 10 / 10)) {
          this.$message.error('数量超过库存数量' + record.maxNum)
          record.num = record.maxNum
        } else {
          let totalPrice = (price * 10 / 10) * (number * 10 / 10)
          record.totalPrice = totalPrice.toFixed(2)
        }
      } else {
        record.totalPrice = 0
      }

      // 计算出合计总价、合计数量
      this.allTotalPrice = 0
      this.allTotalNum = 0
      for (let item of this.materialDataSource) {
        if (ifNumber1(item.num)) {
          this.allTotalPrice += item.totalPrice * 10 / 10
          this.allTotalNum += item.num * 10 / 10
        } else {
          this.allTotalPrice = null
          this.allTotalNum = null
          return
        }
      }
      this.allTotalPrice = (this.allTotalPrice * 10 / 10).toFixed(2)
    },
    HouseSureBack() {//撤销库管确认
      if( !this.material.houseSureUser){
        this.$message.success("还未进行库管确认")
      }
      flowerMaterialOutHouseSureBack(this.material).then(res => {
        if (res.success) {
          this.queryMaterialOutMain()
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
        this.addOrEditVisible = false
      })
    },
    exportExcel(record){
      let  dt = new Date()
      let fileName = '采后物资出库单'+ record.no +"-"+ dt.getFullYear()+"-"+(dt.getMonth()+1)+"-"+dt.getDate()

      let urlss = '/flowermater/flowerMaterialOutMain/exportXlsForTemp'
      downFile(urlss, {id:record.id } ).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    queryFlowerBase(){//获取领用基地
      queryFlowerBase().then(res=>{
        if (res.success) {
          this.sourceBaseList=res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },
    queryGreenhouseByPd(baseId){//获取领用大棚
      queryGreenhouseByPd(baseId).then(res=>{
        if (res.success) {
          this.sourceGreenhouseList=res.result
        } else {
          this.$message.error('未找到对应的领用大棚')
        }
      })
    },
    sourceBaseChange(e){// 选择领用基地的Change
      this.queryGreenhouseByPd(e)
    },
    getPeriod() {
      period().then(res => {
        this.periodList = res
      })
    },
    //账期单选的change
    periodChange(e) {
      this.material.period = e.target.value
    }
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>